package com.gc.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import com.gc.business.domain.CommunityManage;
import com.gc.business.domain.ElevatorRepair;
import com.gc.business.domain.ElevatorTiring;
import com.gc.business.domain.UpkeepInfo;
import com.gc.business.service.IElevatorRepairService;
import com.gc.business.service.IElevatorTiringService;
import com.gc.business.service.IUpkeepInfoService;
import com.gc.common.annotation.Log;
import com.gc.common.base.AjaxResult;
import com.gc.common.base.Result;
import com.gc.common.enums.BusinessType;
import com.gc.common.utils.StringUtils;
import com.gc.common.utils.poi.ExcelUtil;
import com.gc.framework.shiro.service.SysPasswordService;
import com.gc.framework.util.ShiroUtils;
import com.gc.framework.web.base.BaseController;
import com.gc.system.domain.SysUser;
import com.gc.system.service.ISysPostService;
import com.gc.system.service.ISysRoleService;
import com.gc.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author gc
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IUpkeepInfoService upkeepInfoService;

    @Autowired
    private IElevatorRepairService elevatorRepairService;

    @Autowired
    private IElevatorTiringService elevatorTiringService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    /**
     * 跳转归属用户列表
     *
     * @param attrId
     * @param mmap
     * @return
     */
    @GetMapping("/attrUser")
    public String attrUser(Long attrId, ModelMap mmap) {
        mmap.put("attrId", attrId == null ? 0 : attrId);
        return prefix + "/attrUser";
    }

    /**
     * 跳转公司员工列表
     *
     * @param attrId
     * @param mmap
     * @return
     */
    @GetMapping("/companyUser")
    public String companyUser(Long attrId, ModelMap mmap) {
        mmap.put("attrId", attrId == null ? getAttrId() == null ? 0 : getAttrId() : attrId);
        return prefix + "/company/companyUser";
    }

    /**
     * 新增公司用户
     */
    @GetMapping("/companyUserAdd")
    public String companyUserAdd(Long attrId, ModelMap mmap) {
        mmap.put("attrId", attrId);
        mmap.put("roles", userService.selectRoleAndSonList(attrId, null));
        return prefix + "/company/add";
    }

    /**
     * 修改公司用户
     */
    @GetMapping("/companyUserEdit/{userId}")
    public String companyUserEdit(@PathVariable("userId") Long userId, ModelMap mmap) {
        SysUser sysUser = userService.selectUserById(userId);
        mmap.put("user", sysUser);
        mmap.put("roles", userService.selectRoleAndSonList(sysUser.getAttrId(), sysUser.getUserId()));
        return prefix + "/company/edit";
    }

    /**
     * 跳转小区用户列表
     *
     * @param attrId
     * @param mmap
     * @return
     */
    @GetMapping("/communityUser")
    public String communityUser(Long attrId, ModelMap mmap) {
        mmap.put("attrId", attrId == null ? 0 : attrId);
        return prefix + "/community/communityUser";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public Result list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return Result.success(getDataTable(list));
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/communityUserList")
    @ResponseBody
    public Result communityUserList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserListByCommunityAttrId(StringUtils.isNull(getAttrId()) ? 0L : getAttrId());
        return Result.success(getDataTable(list));
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public Result export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(list, "用户数据");
        return Result.success();
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getSysUser().getLoginName();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public Result importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel("用户数据");
        return Result.success();
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(Long attrId, ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.list());
        mmap.put("attrId", attrId);
        mmap.put("role", userService.checkUserRoleByAttrId(attrId));
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult addSave(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", roleService.selectRolesByUserId(userId));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult editSave(SysUser user, Integer flag) {
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        if (StringUtils.isNotNull(flag)) {
            return toAjax(userService.updateUserInfo(user));
        } else {
            return toAjax(userService.updateUser(user));
        }
    }

    /**
     * 修改用户的个人基本信息
     *
     * @param user
     * @return
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/editUserInfo")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult editUserInfo(SysUser user) {
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUserInfo(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        return toAjax(userService.resetUserPwd(user));
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            int row = userService.deleteUserByIds(ids);
            if (row > 0) {
                //删除我的保养
                List<UpkeepInfo> upkeepInfoList = upkeepInfoService.selectListByReviewUserId(ShiroUtils.getUserId(), null);
                List<Long> upkeepIdList = upkeepInfoList.stream().map(UpkeepInfo::getUpkeepId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(upkeepInfoList)){
                    upkeepInfoService.removeByIds(upkeepIdList);
                }
                //删除我的维修
                List<ElevatorRepair> elevatorRepairList = elevatorRepairService.selectListByStatus(ShiroUtils.getUserId(), 3L, null, null, null);
                List<Long> repairIdList = elevatorRepairList.stream().map(ElevatorRepair::getRepairId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(repairIdList)){
                    elevatorRepairService.removeByIds(repairIdList);
                }
                //删除我的救援
                List<ElevatorTiring> myRescueList = elevatorTiringService.findMyRescueList(ShiroUtils.getUserId());
                List<Long> tiringIdList = myRescueList.stream().map(ElevatorTiring::getTiringId).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(tiringIdList)){
                    elevatorTiringService.removeByIds(tiringIdList);
                }
            }
            return toAjax(row);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        return toAjax(userService.changeStatus(user));
    }

    /**
     * 用户可以查看的小区列表
     *
     * @param userId
     */
    @GetMapping("/findCommunityByUserId")
    @ResponseBody
    public Result findCommunityByUserId(Long userId) {
        List<CommunityManage> communityManageList = userService.findCommunityByUserId(userId);
        return Result.success(getDataTable(communityManageList));
    }

    /**
     * 员工审核跳转列表页面
     *
     * @param mmap
     * @return
     */
    @GetMapping("/jumpEmployeesAudit")
    public String jumpEmployeesAudit(ModelMap mmap) {
        mmap.put("attrId", getAttrId() == null ? 0L : getAttrId());
        return prefix + "/audit/auditUser";
    }

    /**
     * 本公司待审核员工列表
     *
     * @param
     * @return
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/userAuditList")
    @ResponseBody
    public Result userAuditList(SysUser user) {
        startPage();
        user.setReviewStatus("1");
        List<SysUser> list = userService.selectUserList(user);
        return Result.success(getDataTable(list));
    }

    /**
     * 员工审核跳转编辑页面
     *
     * @param mmap
     * @return
     */
    @GetMapping("/editAudit")
    public String editAudit(Long userId, ModelMap mmap) {
        SysUser user = userService.selectUserById(userId);
        if (user != null && StringUtils.isNotEmpty(user.getSex())) {
            if (user.getSex().equals("0")) {
                user.setSex("男");
            } else if (user.getSex().equals("1")) {
                user.setSex("女");
            } else if (user.getSex().equals("2")) {
                user.setSex("未知");
            }
        }
        mmap.put("user", user);
        mmap.put("userId", userId);
        mmap.put("roles", userService.selectRoleAndSonList(user.getAttrId(), user.getUserId()));
        return prefix + "/audit/editAudit";
    }
}